package com.txr.news.service.impl;

import com.txr.news.customexception.BusinessException;
import com.txr.news.customexception.SystemException;
import com.txr.news.mapper.UserMapper;
import com.txr.news.pojo.ExType;
import com.txr.news.pojo.Result;
import com.txr.news.pojo.entity.User;
import com.txr.news.pojo.entity.UserExample;
import com.txr.news.service.UserService;
import com.txr.news.utils.JwtUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
    UserMapper userMapper;

    @Override
    public Boolean registerUser(User user) {
        UserExample userExample = new UserExample();
        //1.将用户密码 转换为 md5码
        String newPW = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(newPW);

        //2.查询用户是否存在
        userExample.createCriteria().andUsernameEqualTo(user.getUsername());
        List<User> users = userMapper.selectByExample(userExample);
        if (users != null && !users.isEmpty()){
            //用户已存在
            return false;
        }

        //3.新增用户
        int flag = userMapper.insertSelective(user);
        if (flag != 1){
            throw new SystemException("insert failed", ExType.SystemInsertFail);
        }
        return true;
    }

    @Override
    public Result loginUser(User user) {
        Result result = new Result(0,"login success");

        //1. 根据用户名查询用户的数据
        User dbUser = userMapper.selectByName(user.getUsername());

        if (dbUser == null){
            result.setData(1);
            result.setMsg("用户名或密码错误！");
            return result;
        }

        //2. 判断用户输入的密码是否正确
        String intoPw =  DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
       if ((dbUser.getPassword()).equals(intoPw)){
           //密码正确
           //3. 生成 JWT 的 Token 字符串
           String token = JwtUtils.createToken(dbUser.getId().toString(),dbUser.getUsername());
           result.setToken(token);
       }else{
           result.setStatus(1);
           result.setMsg("用户名或密码错误！");
       }
        return result;
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    @Override
    public User getUserInfo(Integer userId) {
        //Result result = new Result(0,"获取用户信息成功！");
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null){
            throw new BusinessException("user not found by "+userId,ExType.BussRecordNotFound);
        }
        return user;
    }

    /**
     * 更新用户基本信息
     * @param user
     * @return
     */
    @Override
    public Boolean updateUserInfo(User user) {
        //Result result = new Result(0,"更新用户信息成功！");
        int flag = userMapper.updateByPrimaryKeySelective(user);
        if (flag != 1){
            throw new SystemException("update failed", ExType.SystemInsertFail);
        }
        return true;
    }

    /**
     * 修改用户密码：
     * 1、通过userId，查询用户存不存在
     * 2、用户存在 用数据库查询的用户密码与oldPwd比对，不一致要返回 msg:原密码错误
     * 3、比对旧密码成功后，对数据库密码进行更新操作
     */
    @Override
    public Result updateUserPwd(Integer userId, String oldPwd, String newPwd) {
        Result result = new Result(0,"更新密码成功！");
        //1、
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null){
            throw new BusinessException("user not found by "+userId,ExType.BussRecordNotFound);
        }
        //2、
        String md5oldPwd = DigestUtils.md5DigestAsHex(oldPwd.getBytes());
        if (!(user.getPassword()).equals(md5oldPwd)){
            result.setStatus(1);
            result.setMsg("原密码错误！");
        }
        //3、
        String md5newPwd = DigestUtils.md5DigestAsHex(newPwd.getBytes());
        user.setPassword(md5newPwd);
        int flag = userMapper.updateByPrimaryKeySelective(user);
        if (flag != 1){
            throw new SystemException("update failed", ExType.SystemInsertFail);
        }
        return result;
    }

    /**
     * 更新用户头像：
     * 1、通过userId，查询用户存不存在
     * 2、用户存在更新用户头像
     */
    @Override
    public Boolean updateUserPic(Integer userId, String avatar) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null){
            return false;
        }
        user.setUserPic(avatar);
        int flag = userMapper.updateByPrimaryKeySelective(user);
        if (flag != 1){
            throw new SystemException("update failed", ExType.SystemInsertFail);
        }
        return true;
    }
}